﻿using csLTDMC;
using InspectionMAC.Config;
using InspectionMAC.Function;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using InspectionMAC.Forms;
using System.Windows.Forms;
using System.Collections.Concurrent;
using System.IO;
using OfficeOpenXml;


namespace InspectionMAC.SystemThread
    {
        class RecordLocationThread01
        {
            public static bool RecordLocation_Flowrec = false;
            public static Thread RecordLocationFlow_Thread = null;
            public static int iRecordLocation_Step = 0;
            public static bool RecordLocation_Stop = false;
            public static DateTime triggerDataTime;

            private static readonly object _syncLock = new object();
            private static readonly object _excelLock = new object();
            private static BlockingCollection<SingleItemInfo> _dataQueue = new BlockingCollection<SingleItemInfo>(1000);


            public static void RecordLocation_Thread()
            {
                RecordLocation_Flowrec = true;
                RecordLocationFlow_Thread = new Thread(RecordLocationFlowThread) { IsBackground = true };
                RecordLocationFlow_Thread.Start();

                // 启动Excel消费线程
                Task.Factory.StartNew(ProcessExcelQueue, TaskCreationOptions.LongRunning);

                LTDMC.dmc_compare_set_config(0, 0, 1, 1);
                LTDMC.dmc_compare_clear_points(0, 0);
            }

            // Excel队列处理（新增方法）
            private static void ProcessExcelQueue()
            {
                foreach (var item in _dataQueue.GetConsumingEnumerable())
                {
                    try
                    {
                        WriteDataToExcel(item);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Excel保存失败: {ex.Message}");
                    }
                }
            }

            // Excel写入核心逻辑（从原EpplusTest_Form迁移）
            private static void WriteDataToExcel(SingleItemInfo data)
            {
                lock (_excelLock)
                {
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    var filePath = GetDailyExcelPath();
                    var fileInfo = new FileInfo(filePath);

                    using (var package = new ExcelPackage(fileInfo))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets["检测数据"] ?? CreateWorksheet(package);
                        int lastRow = worksheet.Dimension?.Rows ?? 1;
                        WriteDataRow(worksheet, lastRow + 1, data);
                        package.Save();
                    }
                }
            }

            private static string GetDailyExcelPath()
            {
                string appRoot = AppDomain.CurrentDomain.BaseDirectory;
                string saveFolder = Path.Combine(appRoot, "InspectionData");
                Directory.CreateDirectory(saveFolder);
                return Path.Combine(saveFolder, $"Inspection_{DateTime.Now:yyyyMMdd}.xlsx");
            }

            private static ExcelWorksheet CreateWorksheet(ExcelPackage package)
            {
                var worksheet = package.Workbook.Worksheets.Add("检测数据");
                string[] headers = {
                "产品ID", "产品名称",
                "工位一检测时间", "工位一位置", "工位一照片宽度", "工位一照片高度",
                "工位一图片名称", "工位一缺陷类型", "是否不良", "是否保存",
                "工位二检测时间", "工位二位置", "工位二照片宽度", "工位二照片高度",
                "工位二图片名称", "工位二缺陷类型", "是否不良", "是否保存",
                "工位三检测时间", "工位三位置", "工位三照片宽度", "工位三照片高度",
                "工位三图片名称", "工位三缺陷类型", "是否不良", "是否保存"
            };

                for (int i = 0; i < headers.Length; i++)
                {
                    worksheet.Cells[1, i + 1].Value = headers[i];
                    worksheet.Cells[1, i + 1].Style.Font.Bold = true;
                }
                return worksheet;
            }

            // 数据行写入（从原EpplusTest_Form迁移）
            private static void WriteDataRow(ExcelWorksheet ws, int row, SingleItemInfo data)
            {
                int col = 1;

                ws.Cells[row, col++].Value = data.ID;
                ws.Cells[row, col++].Value = data.Name;
                ws.Cells[row, col++].Value = data.CameraResult01.DataTime;
                ws.Cells[row, col++].Value = data.CameraResult01.Location;
                ws.Cells[row, col++].Value = data.CameraResult01.iWidth;
                ws.Cells[row, col++].Value = data.CameraResult01.iHeight;
                ws.Cells[row, col++].Value = data.CameraResult01.iName;
                ws.Cells[row, col++].Value = data.CameraResult01.Faults;
                ws.Cells[row, col++].Value = data.CameraResult01.isNG ? "NG" : "OK";
                ws.Cells[row, col++].Value = data.CameraResult01.isOkSave ? "是" : "否";

                // 工位二数据
                ws.Cells[row, col++].Value = data.CameraResult02.DataTime;
                ws.Cells[row, col++].Value = data.CameraResult02.Location;
                ws.Cells[row, col++].Value = data.CameraResult02.iWidth;
                ws.Cells[row, col++].Value = data.CameraResult02.iHeight;
                ws.Cells[row, col++].Value = data.CameraResult02.iName;
                ws.Cells[row, col++].Value = data.CameraResult02.Faults;
                ws.Cells[row, col++].Value = data.CameraResult02.isNG ? "NG" : "OK";
                ws.Cells[row, col++].Value = data.CameraResult02.isOkSave ? "是" : "否";

                // 工位三数据
                ws.Cells[row, col++].Value = data.CameraResult03.DataTime;
                ws.Cells[row, col++].Value = data.CameraResult03.Location;
                ws.Cells[row, col++].Value = data.CameraResult03.iWidth;
                ws.Cells[row, col++].Value = data.CameraResult03.iHeight;
                ws.Cells[row, col++].Value = data.CameraResult03.iName;
                ws.Cells[row, col++].Value = data.CameraResult03.Faults;
                ws.Cells[row, col++].Value = data.CameraResult03.isNG ? "NG" : "OK";
                ws.Cells[row, col++].Value = data.CameraResult03.isOkSave ? "是" : "否";

                ws.Cells[ws.Dimension.Address].AutoFitColumns();
            }
        private static void RecordLocationFlowThread(object obj)
        {
            while (RecordLocation_Flowrec)
            {
                var currentItem = new SingleItemInfo();
                switch (iRecordLocation_Step)
                {
                    
                    case 0:
                         
                        break;

                    case 10:
                        //LTDMC.dmc_compare_clear_points(0, 0);
                        if (DIO_Thread.Di[11] == 1)
                        {
                            triggerDataTime = DateTime.Now;
                            UInt32 nEnPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);

                            LTDMC.dmc_compare_add_point(0, 0, LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0) + 56771, 1, 2, 1);
                            LTDMC.dmc_compare_add_point(0, 0, LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0) + 94938, 1, 2, 2);
                            LTDMC.dmc_compare_add_point(0, 0, LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0) + 146092+26547, 1, 2, 3);
                            
                            //DIO_Thread.Do[1] = 0;
                            //iRecordLocation_Step = 15;
                        }
                        break;
                   
                }
            }
        }
    }
}
